#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3014 source=/dev/null
#
# raspi-fanshim daemon starting and stopping
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin

DAEMON="raspi-fanshim"
PIDFILE="/var/run/${DAEMON}.pid"

test -e /etc/config/enableFanshim || exit 0
test -x /opt/raspi-fanshim/FanshimService || exit 0

case $1 in
	start)
		echo -n "Starting Fan SHIM daemon: "

		# source all data from /var/hm_mode
		[[ -r /var/hm_mode ]] && . /var/hm_mode

		if [[ "${HM_HMRF_DEV}" == "HM-MOD-RPI-PCB" ]] ||
			[[ "${HM_HMIP_DEV}" == "HM-MOD-RPI-PCB" ]]; then
			echo "ERROR: parallel use of Fan SHIM + HM-MOD-RPI-PCB not possible!"
		else
			# now start the daemon
			if start-stop-daemon --start --background --pidfile "${PIDFILE}" --make-pidfile --quiet --exec "/opt/raspi-fanshim/FanshimService"; then
				echo "OK"
			else
				echo "FAIL"
			fi
		fi
	;;

	stop)
		echo -n "Stopping Fan SHIM daemon: "
		if [[ -f ${PIDFILE} ]]; then
			if start-stop-daemon --stop --quiet --pidfile "${PIDFILE}"; then
				echo "OK"
			else
				echo "FAIL"
			fi
			rm -f "${PIDFILE}"
		else
			echo "OK"
		fi
	;;

	restart|force-reload)
		$0 stop
		sleep 1
		$0 start
	;;

	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 1
	;;
esac

exit 0
